package com.qs.sckill.service.impl;

import com.qs.sckill.config.redis.key.UserKey;
import com.qs.sckill.dao.UserDao;
import com.qs.sckill.entity.User;
import com.qs.sckill.exception.GlobalException;
import com.qs.sckill.result.CodeMsg;
import com.qs.sckill.service.RedisService;
import com.qs.sckill.service.UserService;
import com.qs.sckill.utils.MD5Util;
import com.qs.sckill.utils.UUIDUtil;
import com.qs.sckill.utils.WebConstants;
import com.qs.sckill.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Resource
    private RedisService redisService;

    @Override
    public User getUserByPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new GlobalException(CodeMsg.PARAMETER_CHECK_ERROR);
        }

        return userDao.getUserByPhone(phone);
    }

    @Override
    public boolean login(HttpServletResponse response, LoginVo loginVo) {
        if (loginVo == null) {
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }

        String mobile = loginVo.getMobile();
        String formPass = loginVo.getPassword();
        User user = getUserByPhone(mobile);
        if (user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }

        //判断表单输入加密后的密码和数据库中存储的密码是否一致
        String dbPass = user.getPassword();
        String saltDB = user.getSalt();
        String calcPass = MD5Util.formPassToDBPass(formPass, saltDB);
        if (!calcPass.equals(dbPass)) {
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }

        //登录成功后，生成token，存储在cookie中（分布式session使用redis）
        String token = UUIDUtil.uuid();
        addCookie(response, token, user);
        return true;
    }

    @Override
    public User getByToken(HttpServletResponse response, String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }

        //根据token获取到用户信息，则顺延cookie失效时间（cookie和redis失效时间）
        User user = redisService.get(UserKey.token, token, User.class);
        if (user != null) {
            addCookie(response, token, user);
        }

        return user;
    }

    @SuppressWarnings("unchecked")
    private void addCookie(HttpServletResponse response, String token, User user) {
        redisService.set(UserKey.token, token, user);
        Cookie cookie = new Cookie(WebConstants.COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(UserKey.token.expireSeconds());
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
